import axios from "axios"
import Qs from "qs"

import store from "../vuex/store"
import Router from "../unit/router"

import { Message } from 'element-ui';

const instance = axios.create({
    baseURL: '/api',
    timeout: 1000000,
    withCredentials: false,
    auth: {},
    responseType: 'json',
    responseEncoding: 'utf8',
    paramsSerializer: function (params) {
        return Qs.stringify(params)
    },
    onUploadProgress: function (progressEvent) { },
    onDownloadProgress: function (progressEvent) { },
    maxContentLength: 2000,
    validateStatus: function (status) {
        return status >= 200 && status < 300
    }
});
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
instance.interceptors.request.use(function (config) {
    if (store.state.user.token) {
        config.headers = { token: store.state.user.token }
    }
    return config
}, function (error) {
    return Promise.reject(error)
});

instance.interceptors.response.use(function (response) {
    if (response.data.code === 200) {
        return response.data
    } else if (response.data.code === 405 || response.data.code === 406 || response.data.code === 407) {
        Message(response.data.message)
        Router.push("/login");
        return
    } else {
        Message(response.data.message)
    }
}, function (error) {
    if (error.message.includes('timeout')) {
        Message("网络不给力，请重试！")
        return Promise.reject(error);
    }

    Message(error.message)
    return Promise.reject(error)
});

async function getData(url, method, params = {}) {
    if(method === "postBody"){
        return instance({
            url: url,
            method: "POST",
            data: params
        })
            .then(function (response) { return response })
            .catch(function (error) { return error });
    }else{
        return instance({
            url: url,
            method: method,
            params: params
        })
            .then(function (response) { return response })
            .catch(function (error) { return error });
    }
    
}

export {
    getData
}



